<?php
include '../class/class.dokumen.php';
session_start();

$id_user=$_SESSION['id_user'];
$error = "";
$msg = false;
$ekstensi = array('pdf', 'PDF', 'jpg', 'jpeg');
$direktori = 'dokumen';
$size = 2000000; //2mb
if (empty($_FILES['file_dokumen']['tmp_name']) || $_FILES['file_dokumen']['tmp_name'] == 'none') {
    $error = 'File Tidak Ada';
} elseif (empty($_POST['judul'])) {
    $error = 'Deskripsi File Harus Diisi';
} else {
    $id_usulan = $_POST['id_usulan'];
    $judul = $_POST['judul'];

    $tmp = explode('.', $_FILES['file_dokumen']['name']);
    $fileEks = $tmp[count($tmp) - 1];
    $fileName = $tmp[0];
    $nama_file = $id_user."_".$id_usulan."_".$_FILES['file_dokumen']['name'];

    if (in_array($fileEks, $ekstensi)) {
        if ($_FILES['file_dokumen']['size'] <= $size) {

            if (file_exists('../dokumen/' . $nama_file)) {
                $error = "File Sudah Ada, Silahkan Hapus File Dahulu";
            } else {
                
                $save = move_uploaded_file($_FILES['file_dokumen']['tmp_name'], '../' . $direktori . '/' . $nama_file);
                if($save){
                    $dokumenDao= new DokumenDao();
                    $simpan=$dokumenDao->saveDokumen($judul,$nama_file,$id_usulan);
                    if($simpan){
                        $msg=true;
                    }else{
                        $error="Gagal Simpan File";
                        @unlink('../' . $direktori . '/' . $nama_file);
                    }
                }else{
                    $error="Gagal Simpan File";
                }
            }
        } else {
            $error = 'Maksimal Ukuran File 2mb';
        }
    } else {
        $error = 'Format File hanya PDF, JPG dan JPEG';
    }


    @unlink($_FILES['file_dokumen']);
}

$data = array(
    'error' => $error,
    'msg' => $msg,
);

echo json_encode($data);
?>
